package com.alogic.xscript.plugins;

import org.apache.commons.lang3.StringUtils;

import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import com.anysoft.util.Settings;

/**
 * 向Settings中设置变量
 * 
 * @author yyduan
 * @since  1.6.12.6 [20181105 duanyy] <br>
 */
public class SetSettings extends AbstractLogiclet {
	protected String $id;	
	protected boolean raw = false;
	protected boolean ref = false;
	protected String $value;
	protected String $dft;
	protected String $final="false";
	
	public SetSettings(String tag, Logiclet p) {
		super(tag, p);
	}

	public void configure(Properties p){
		super.configure(p);
		
		$id = PropertiesConstants.getRaw(p,"id","");
		$value = PropertiesConstants.getRaw(p,"value","");
		raw = PropertiesConstants.getBoolean(p, "raw", raw);
		ref = PropertiesConstants.getBoolean(p, "ref", ref);
		$dft = PropertiesConstants.getRaw(p,"dft","");
		$final = PropertiesConstants.getRaw(p,"final",$final);
	}

	@Override
	protected void onExecute(XsObject root,XsObject current, LogicletContext ctx, ExecuteWatcher watcher) {
		String id = PropertiesConstants.transform(ctx, $id, "");
		if (StringUtils.isNotEmpty(id)){
			Settings settings = Settings.get();
			boolean isFinal = PropertiesConstants.transform(ctx, $final, false);			
			String oldValue = settings.GetValue(id, "");
			if (StringUtils.isEmpty(oldValue) || !isFinal){
				String value;
				if (raw){
					value = ref?PropertiesConstants.getRaw(ctx, $value, $dft):$value;
				}else{
					String v = PropertiesConstants.transform(ctx,$value,"");
					String dft = PropertiesConstants.transform(ctx,$dft,"");
					if (StringUtils.isEmpty(v)){
						v = dft;
					}
					value = ref?PropertiesConstants.getString(ctx,v,dft,false):v;
				}
				settings.SetValue(id, value);
			}
		}
	}
}
